package ipc

import "fmt"
import "encoding/json"

type Request struct {
	Method string `json:"method"`
	Params string `json:"params"`
}

type Response struct {
	Code string `json:"code"`
	Body string `json:"body"`
}

type Server interface { //定义接口，确定业务要实现的统一接口
	Name() string
	Handle(method, params string) *Response
}

type IpcServer struct {
	Server
}

func NewIpcServer(server Server) *IpcServer { //构造方法

	return &IpcServer{server}
}

func (server *IpcServer) Connect() chan string {

	session := make(chan string, 0)

	go func(c chan string) {

		for {
			request := <-c // channel 中读取数据,没读取到数据会阻塞

			if request == "CLOSE" { //关闭连接
				break
			}

			var req Request

			err := json.Unmarshal([]byte(request), &req)

			if err != nil {
				fmt.Println("Invalid request format:", request)
				return
			}

			resp := server.Handle(req.Method, req.Params) //执行请求

			b, err := json.Marshal(resp)

			c <- string(b) //返回结果

		}

		fmt.Println("Session closed.")

	}(session)

	fmt.Println("A new session has been created successfully.")

	return session
}
